/*
 * @Author: xiaoyan
 * @Date: 2021-09-08 18:08:47
 * @LastEditors: xiaoyan
 * @LastEditTime: 2021-09-10 15:59:43
 * @Description: 用户
 * @FilePath: \vue-ts-basic\src\store\modules\user.ts
 */
import { VuexModule, Module, Mutation, Action, getModule } from 'vuex-module-decorators'
import {login,getUserInfo,logout} from '@/api'
import { getToken, setToken, removeToken } from '@/utils/storage'
import store from '@/store'

export interface IUserState{
    token:string
    name:string
    avatar:string
    roles:string[]
}

@Module({ dynamic: true, store, name: 'user' })
class User extends VuexModule implements IUserState {
    public token = getToken() || ''
    public name = ""
    public avatar = ""
    public roles:string[] = []

    @Mutation
    private SET_TOKEN(token:string){
        this.token = token
    }
    @Mutation
    private SET_NAME(name:string){
        this.name = name
    }
    @Mutation
    private SET_AVATAR(avatar:string){
        this.avatar = avatar
    }
    @Mutation
    private SET_ROLES(roles:string[]){
        this.roles = roles
    }

    @Action
    public async Login(userInfo:{username:string,password:string}){
        const {username,password} = userInfo;
        const { data } = await login({username,password});
        setToken(data.accessToken)
        this.SET_TOKEN(data.accessToken)
    }
    @Action
    public async GetUserInfo(){
        const { data } = await getUserInfo();
        const { roles, name, avatar } = data.user;
        this.SET_ROLES(roles);
        this.SET_NAME(name);
        this.SET_AVATAR(avatar);
    }
    @Action
    public async LogOut(){
        await logout();
        removeToken();
        this.SET_TOKEN('');
    }
}
export const UserModule = getModule(User)